package com.swsc.solarverse.schedule;

import com.swsc.solarverse.common.config.ResParams;
import com.swsc.solarverse.model.CorporationStationBO;
import com.swsc.solarverse.service.schedule.StringLeDiagnoseScheduleTaskService;
import org.apache.commons.collections4.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author Administrator
 * @Date 2025/7/22 17:06
 * @Version 1.0
 * @Description 低效诊断
 */
@lombok.extern.slf4j.Slf4j
@org.springframework.stereotype.Component
public class StringLeDiagnoseScheduleTask {
    private final StringLeDiagnoseScheduleTaskService stringLeDiagnoseScheduleTaskService;

    public StringLeDiagnoseScheduleTask(StringLeDiagnoseScheduleTaskService stringLeDiagnoseScheduleTaskService) {
        this.stringLeDiagnoseScheduleTaskService = stringLeDiagnoseScheduleTaskService;
    }

    /**
     * 每天凌晨2点将昨天组串低效分析结果保存到故障表
     * 前置任务1: 组串能效计算 StringEfficiencyRecordAnalysisScheduledTask#analysisString, 每天18点执行
     * 前置任务2: 组串低效分析 StringIuAnalysisScheduleTask#analysisNew, 每天21点执行(需要连续3天的组串能效计算结果)
     */
    @org.springframework.scheduling.annotation.Async
    @org.springframework.scheduling.annotation.Scheduled(cron = "0 0 2 * * ?")
    public void diagnose() {
        if (!ResParams.getScheduleTaskLeDiagnoseEnable()) {
            log.warn("低效诊断-未开启低效诊断...");
            return;
        }
        List<CorporationStationBO> corporationDos = stringLeDiagnoseScheduleTaskService.listCorporationStations();
        if (CollectionUtils.isNotEmpty(corporationDos)) {
            LocalDateTime now = LocalDateTime.now();
            for (CorporationStationBO stationBo : corporationDos) {
                try {
                    stringLeDiagnoseScheduleTaskService.diagnose(stationBo,
                            now.minusDays(1L).withHour(0).withMinute(0).withSecond(0).withNano(0),
                            now);
                } catch (Exception e) {
                    log.error("低效诊断[{}]-错误", stationBo.getOrganNo(), e);
                }
            }
        }
    }
}
